<?php
//PingBuWang.Com
//Copyright (c) 2017~2099 http://www.pingbuwang.com All rights reserved.
namespace app\user\controller;
use app\user\model\Users;
use app\user\model\UsersGroup;
use com\EmailUtils;
use com\EncryptUtils;
use com\SmsUtils;
use PHPMailer\PHPMailer\Exception;
use think\Log;
use think\Request;
use think\Loader;
use think\Session;
use think\Cache;
use mip\Htmlp;
use mip\ApiBase;


class ApiUserUser extends ApiBase
{
    public function index(){

    }
    public function do_login(Request $request) {
        if (Request::instance()->isPost()) {
            $username = input('post.username');
            $password = input('post.password');
            $captcha = input('post.captcha');
            $rules = [
                'username'  => 'require',
                'password'  => 'require',
            ];
            $msg = [
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
            ];
            $result = $this->validate($request->param(), $rules, $msg);
            if (true !== $result) {
                return $result;
            }

            if(!captcha_check($captcha)){
                return jsonError('验证码错误');
            }

            // 用户名和密码验证
            $userInfo = Loader::model('app\user\model\Users')->loginUser($username,$password);
            if ($userInfo) {
                if (!$this->mipInfo['loginStatus']) {
                    if ($userInfo['group_id'] != 1) {
                        return jsonError('本站已关闭登录');
                    }
                }
                if($userInfo['status']==1){
                    return jsonError('你的账号被禁止登录');
                }

                $user['uid']       = $userInfo['uid'];
                $user['username']  = $userInfo['username'];
                $user['nickname']  = $userInfo['nickname'];

                if ($userInfo['group_code'] < 100) {
                    $user['isAdmin'] = true;
                } else {
                    $user['isAdmin'] = false;
                }

                $userInfo['password'] = null;
                $userInfo['salt'] = null;

                session('userInfo',$user);
                return jsonSuccess('登录成功',$userInfo);
            } else {
                return jsonError('账号或密码不正确');
            }
        }
    }

    /**
     * 为找回密码而获取验证码
     * find_type支持  email 和 mobile
     */
    public function send_chgpwdcaptcha(){

        $findType=input('post.findType');
        $email=input('post.email');
        $mobile = input('post.mobile');
        $captcha = input('post.captcha');

        if(!captcha_check($captcha)){
            return jsonError('验证码输入错误');
        }

        $chgPwdCaptcha = EncryptUtils::rndStr(6,2);
        $msg = "您的验证码是：$chgPwdCaptcha 请不要把验证码泄露给其他人，如非本人操作，可不用理会！";

        // 发送短信
        if($findType=='mobile'){
            $u = db('users')->where('mobile',$mobile)->find();
            if($u==null){
                return jsonError('手机号：'.$mobile.'不存在。');
            }

            SmsUtils::send($mobile,$msg,$this);
            // 将验证码放入缓存中，10分钟过期
            $val=['find_type'=>$findType,'mobile'=>$mobile,'email'=>$email,'chgPwdCaptcha'=>$chgPwdCaptcha];
            Cache::set(session_id().'_chgPwdCaptcha',$val,600);
            return jsonSuccess('验证码已经发送，请输入验证码');
        }

        // 发送电子邮件
        if($findType=='email'){
            $u = db('users')->where('email',$email)->find();
            if($u==null){
                return jsonError('电子邮箱号：'.$email.'不存在。');
            }

            EmailUtils::send($email,$u['nickname'],'平步科技验证码',$msg,$this);
            // 将验证码放入缓存中，10分钟过期
            $val=['findType'=>$findType,'mobile'=>$mobile,'email'=>$email,'chgPwdCaptcha'=>$chgPwdCaptcha];
            Cache::set(session_id().'_chgPwdCaptcha',$val,600);
            return jsonSuccess('验证码已经发送，请登录您的电子邮箱，并获取密码重置验证码');
        }

        return jsonError('find_type必须为mobile或email');

    }

    public function chg_pwd_by_captcha(){

        $chgPwdCaptcha = input('chgPwdCaptcha');
        $newPassword = input('newPassword');

        $val=Cache::get(session_id().'_chgPwdCaptcha');

        if($val==null){
            return jsonError('您的密码重置验证码不存在或已过期，请重新获取密码重置验证码。');
        }

        if($val['chgPwdCaptcha']!=$chgPwdCaptcha){
            return jsonError('您的密码重置验证码错误。');
        }

        if($val['findType']=='mobile'){
            $salt=EncryptUtils::rndStr(8);
            $pwd = create_md5($newPassword,$salt);
            db('users')->where('mobile',$val['mobile'])->update(['password'=>$pwd,'salt'=>$salt]);

        }

        if($val['findType']=='email'){
            $salt=EncryptUtils::rndStr(8);
            $pwd = create_md5($newPassword,$salt);
            db('users')->where('email',$val['email'])->update(['password'=>$pwd,'salt'=>$salt]);

        }

        return jsonSuccess('密码修改成功');

    }
}